package com.bhf.utils;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author pwq
 */
public class HttpClientUtil {

    public static String get(String url, Map<String,Object> params) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpClientContext context = HttpClientContext.create();
        if (params!=null){
            params.forEach(context::setAttribute);
        }
        try (CloseableHttpResponse response = httpclient.execute(httpGet, context)) {
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
                return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        }
        return null;
    }

    public static String get(String url) throws IOException {
        return get(url,null);
    }


    public static String post(String url) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("username", "vip"));
        nvps.add(new BasicNameValuePair("password", "secret"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
                return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        }
        return null;
    }
}
